<template>
    <div id="novel_details">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item>作品管理</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <el-row :gutter="20">
                <el-col :span="this.$store.state.elColNum">
                    <el-form ref="form" :model="form" :label-width="this.$store.state.labelWidth" size="small">
                        <el-form-item label="小说标题">
                            <el-input v-model="form.title"></el-input>
                        </el-form-item>
                      <el-form-item label="小说封面图链接">
                        <div class="custom-upload-btn" @click="handleTouchStart">
                          <i v-if="!form.coverpic" class="el-icon-plus avatar-uploader-icon"></i>
                          <el-upload
                              ref="uploadRef"
                              class="avatar-uploader"
                              action="upDataUrl"
                              :show-file-list="false"
                              :http-request="myUpload1"
                              accept="image/jpeg,image/png,image/jpg"
                              :before-upload="beforeAvatarUpload">
                            <img v-if="form.coverpic" :src="form.coverpic" class="cover" alt="">
                          </el-upload>
                        </div>
                      </el-form-item>
                        <el-form-item label="小说描述">
                            <el-input v-model="form.desc" :autosize="{ minRows: 4}" type="textarea"></el-input>
                        </el-form-item>
                      <el-form-item label="" :class="this.$store.state.windowWidth <= this.$store.state.MaxWidth ? 'maxWidth' : ''">
                        <el-select v-model="primaryCategory" placeholder="请选择一级分类" clearable @change="loadSecondaryCategories">
                          <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="" :class="this.$store.state.windowWidth <= this.$store.state.MaxWidth ? 'maxWidth' : ''">
                        <el-select v-model="secondaryCategory" placeholder="请选择二级分类" clearable>
                          <el-option v-for="category in secondaryCategories" :key="category.id" :label="category.name" :value="category.id"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="自定义标签">

                        <div>
                          <span v-for="(label) in strLabel" style="margin: 5px 10px;background-color: #f5f5f5">{{label}}</span>
                        </div>
                        <el-input placeholder="/分割，例：奇幻/破镜重圆" v-model="labels" @input="handleLabels"></el-input>
                      </el-form-item>
                      <el-form-item label="一句话推荐语">
                        <el-input v-model="form.recommend_word"></el-input>
                      </el-form-item>
                      <el-form-item label="审核不通过原因" v-if="form.fail_reason">
                        {{form.fail_reason}}
                      </el-form-item>

                      <el-button @click="back" size="small">返回</el-button>
                      <el-button type="primary" @click="onSubmit" size="small" v-if="version || !id">保存草稿</el-button>
                      <el-button type="success" @click="onPush" size="small">提交审核</el-button>
                    </el-form>
                </el-col>
            </el-row>
        </el-card>
    </div>
</template>

<style scoped>
.custom-upload-btn {
  width: 150px; /* 根据需要调整 */
  height: 200px; /* 根据需要调整 */
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: #8c939d dotted 1px;
}

.cover {
  width: 150px; /* 根据需要调整 */
  height: 200px; /* 根据需要调整 */
  overflow: hidden; /* 隐藏超出容器的部分 */
  position: relative; /* 使得子元素可以相对于此容器定位 */
}

.cover img {
  width: 100%; /* 图片宽度等于容器宽度 */
  object-fit: cover; /* 保持图片的原始比例，同时填充整个容器 */
  position: absolute; /* 绝对定位，使得图片可以填充整个容器 */
  top: 0; /* 图片顶部与容器顶部对齐 */
  left: 0; /* 图片左侧与容器左侧对齐 */
}
</style>

<script>
  import {uploadimg, isRealNum} from "../../utils/common";

  export default {
    name: "novel_details",
    data() {
      return {
        form: {
          title: '',
          version:'',
          id:'',
          coverpic: '',
          cateids: [],
          isfw: '',
          issex: '',
          tag: '',
          iswz: '1',
          is_fanwork:'',
          isbg: '',
          remark: '',
          list_order: '',
          desc: '',
          paychapter: '',
          thermal: '',
          hots: '',
          likes: '',
          sharetitle: '',
          sharedesc: '',
          tchapter: '',
          coin: '',
          isrecommend: '',
          recommend_word:'',
          fail_reason: '',
          ishow: '',
          status: '',
          labels:'',
          secondary_cateid:'',
        },
        channel_id: '',
        classList: [],
        cateids: [],
        labels:'',
        strLabel:'',

        areaIds: [],
        id: '',
        version: 0,
        primaryCategory: '', // 一级分类
        secondaryCategory: '', // 二级分类
        secondaryCategories:[],
        categories: [], // 一级
        categoriesall: [] // 存储所有分类数据
      }
    },
    created() {
      this.getCategoryList();
      this.id = this.$route.query.id;
      this.version = this.$route.query.version;

      if (this.id) {
        this.$axios.get('writer/novel/detail', {id: this.id, version: this.version}).then((res) => {
          let data = res.data;
          for (let key in data) {
            if (isRealNum(data[key])) {
              data[key] = data[key].toString()
            }
          }


          this.form = data;
          this.form.id = this.id


          if (data.labels != null) {
            this.strLabel = data.labels.split(',')
            this.labels = this.strLabel.join('/')
          }

          this.primaryCategory = Number(this.form.cateids)
          this.loadSecondaryCategories()
          this.secondaryCategory = Number(this.form.secondary_cateid)

          this.$forceUpdate()
        })
      }
    },
    methods: {
      onSubmit() {


        if (this.labels) {

          let strLabel1 = this.labels.split('/');
          let strLabel2 = this.labels.split(';');
          let strLabel3 = this.labels.split(' ');
          let strLabel4 = this.labels.split(',');

          this.strLabel = this.findLongestArray(strLabel1, strLabel2, strLabel3, strLabel4)
          this.form.labels =this.strLabel.join(',');
        }

        if (!this.checkForm()) {
          return
        }

        this.$axios.post("writer/novel/save-draft", this.form).then((res) => {
          this.$message.success('成功');
          this.back()
        }, (err) => {

        });

      },
      findLongestArray(...args) {
    let longest = null;
    let longestLength = 0;

    // 遍历传入的数组参数
    for (let i = 0; i < args.length; i++) {
      const array = args[i];

      // 确保参数是一个数组
      if (Array.isArray(array)) {
        // 如果当前数组长度大于已知的最长长度
        if (array.length > longestLength) {
          longest = array; // 更新最长数组
          longestLength = array.length; // 更新最长长度
        }
      }
    }

    // 如果没有找到任何数组，返回null或者一个空数组
    return longest || [];
  },
  handleTouchStart() {
        // 获取 el-upload 组件内部的文件输入元素
        const inputElement = this.$refs.uploadRef.$el.querySelector('input[type="file"]');

        // 触发文件输入元素的点击事件
        inputElement.click();
      },
      getCategoryList() {
        this.$axios.post("admin/novel/novelcategoryall").then(res => {

          // 将接口返回的分类数据存储到 categories 中
          this.categories = res.data[2].list.filter(category => category.parent_id === null);
          this.categoriesall = res.data[2].list;

        })
      },
      loadSecondaryCategories() {
        // 清空二级类别数据
        this.secondaryCategory = '';


        // 找到所选一级类别的 id
        const selectedPrimaryCategoryId = this.primaryCategory;

        // 根据所选一级类别的 id，筛选出对应的二级类别数据
        if (selectedPrimaryCategoryId) {
          this.secondaryCategories = this.categoriesall.filter(category => category.parent_id === selectedPrimaryCategoryId);
        } else {
          this.secondaryCategories = []; // 如果没有选择一级类别，则清空二级类别数据
        }
      },

      checkForm() {

        if (this.form.title === '') {
          this.$message.error('未填写标题');
          return  false
        }
        if (this.form.desc  === '') {
          this.$message.error('未填写简介');
          return false
        }

        if (this.primaryCategory === '') {
          this.$message.error('未选择一级分类');
          return false
        }


        return true

      },

      onPush(){
        if (this.cateids) {
          this.form.cateids = this.cateids.join(',');
        }
        if (this.labels) {
          this.strLabel = this.labels.split('/');
          this.form.labels =this.strLabel.join(',');
        }

        this.form.cateids = this.primaryCategory
        this.form.secondary_cateid = this.secondaryCategory

        if (!this.checkForm()) {
          return
        }



        this.$axios.post("writer/novel/push",  this.form).then((res) => {
          this.$message.success('发布成功');
          this.back()
        }, (err) => {

        });
      },

      handleLabels() {
        this.strLabel = this.labels.split('/');
      },

      getCateIds() {
        this.$axios.post("writer/novel/category").then((res) => {
          if (res.data) {
            this.classList = Object.entries(res.data).map(([key, value]) => ({
              label: key, // 使用对象的键作为 label
              value: value // 使用对象的值作为 value
            }));
          }

        });
      },
      myUpload1(content) {
        uploadimg(content).then(res => {
          this.form.coverpic = res;
        })
      },
      beforeAvatarUpload(file) {
        var suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
        let arr = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'pdf', 'JPG', 'JPEG', 'PNG', 'GIF', 'BMP', 'PDF']
        if (arr.indexOf(suffix) === -1) {
          this.$message.error('上传图片格式有误');
          return false
        }
      },
      html_decode(str) {
        var s = "";
        if (str.length == 0) return "";
        s = str.replace(/&amp;/g, "&");
        s = s.replace(/&lt;/g, "<");
        s = s.replace(/&gt;/g, ">");
        s = s.replace(/&nbsp;/g, " ");
        s = s.replace(/&#39;/g, "\'");
        s = s.replace(/&quot;/g, "\"");
        s = s.replace(/<br\/>/g, "\n");
        return s;
      },
      back() {
        this.$router.go(-1)
      }
    }
  }
</script>

<style scoped>

</style>